<template>
	<view class="container">

		<view class="back-btn yticon icon-zuojiantou-up" @click="navBack"></view>
		
		<view class="input-forms">
			<label class="txz-label2">实名认证</label>
			<QSInput :name="formName" 
				variableName="userName" 
				title="姓名"
				placeholder="请输入真实姓名"
				leftIcon="person-filled" 
				titleHide
				required 
				v-model="values.userName" 
				verifyType="Required"
				:itemDisabled="itemDisabled">
			</QSInput>
			<QSInput 
				:name="formName" 
				variableName="idCard" 
				title="身份证号" 
				placeholder="请输入身份证号" 
				leftIcon="contact"
				titleHide required 
				v-model="values.idCard" 
				verifyType="idCart"
				:itemDisabled="itemDisabled"></QSInput>
			
			<QSPics ref="sfzInfPics"
				:name="picsFormName"
				variableName="sfzPics" 
				title="身份证" 
				v-model="sfzPics"
				@imageChoosed="sfzImageChoosed"
				>
			</QSPics>
			
			
			<button type="primary" style="margin-top: 50upx;width: 50%;" @tap="commitForm">提交</button>
			
		</view>
	</view>

	
</template>

<script>
	import QSApp from '@/components/QS-inputs-split/js/app.js';
	import {
		mapState,
		mapGetters,
		mapMutations
	} from 'vuex';
	
	export default {
		computed: {
		    ...mapState(['hasLogin']),
			...mapGetters(['getUserInfo','getWxUserId'])
		},
		data() {
			return {
				title: 'Hello',
				formName: 'realNameInput',
				picsFormName: "realNamePicForm",
				values: {
					userName: '',
					idCard: '',
				},
				itemDisabled: false,
				nCode: '',
				
				sfzPics:[
					{
						title: '正面（国徽）', 
						required: true,
						// path: "http://www.dogroot.com/zdcl-wx/upimg/2020/08/22/00/a4206dc6-f04c-4dc7-9466-4b1a62cdb082.jpg"
					}, 
					{
						title: '反面（头像）',
						required: true,
					 }
				],
				localUserInf: null,
			}
		},
		onShow() {
			let _this = this;
			
			let userInfo = _this.$api.globalData['userInfo']
			if(userInfo==undefined){
				userInfo = uni.getStorageSync('userInfo')
				_this.$api.globalData['userInfo'] = userInfo
				console.log("Storage userInfo:"+JSON.stringify(userInfo))
			}else{
				console.log("Mem userInfo:"+JSON.stringify(userInfo))
			}
			//let localUserInf = _this.getUserInfo;
			_this.localUserInf = userInfo;
		},
		onLoad(options) {
			let _this = this;
			console.log("register onLoad")
		},
		methods: {
			verifyShzId(res){
				console.log('verifyShzId:' + JSON.stringify(res));
				return true;
			},
			// 解析URL 参数
			getUrlParam(name) {
				let reg = new RegExp('(^|&)'+ name + '=([^&]*)(&|$)')
				let r = window.location.search.substr(1).match(reg)
				if(r!=null){
					return unescape(r[2])
				} 
				return null
			},
			sfzImageChoosed(res){
				// console.log('sfzImageChoosed:' + JSON.stringify(res));
				// let _this = this;
				// let fileDescribe = "身份证" + res.title;
				// _this.$refs.sfzInfPics.setUpLoadData({fileDescribe:fileDescribe});
				// const upload = this.$refs.sfzInfPics.getUpLoadPromiseArray();
				// upload.then(res=>{
				// 	console.log('上传成功:' + JSON.stringify(res));
					
				// 	console.log('更新:' + JSON.stringify(_this.sfzPics));
				// }).catch(err=>{
				// 	console.log('上传失败:' + JSON.stringify(err));
				// })
			},
			commitInputForm(){
				let _this = this;
				QSApp.getForm(_this.formName).then(res => {
					console.log('获取输入:' + JSON.stringify(res));	
					// if(res.data.userName == null || res.data.userName == '' ||
					//  res.data.idCard == null || res.data.idCard == ''
					// ){
					// 	QSApp.showToast('输入信息不完整');
					// 	return;
					// }
					if(res.verifyErr.length>0){
						let errInput = res.verifyErr[0];
						QSApp.showToast(errInput.title + "输入不正确");
						return;
					}
					
					//temp test
					//return;
					
					let params = {
						userName: res.data.userName,
						idCard: res.data.idCard,
						idCardFront:"",
						idCardReverse: "" ,
					};
					//debugger;
					//填充图片提交结果
					try{
						let uploadRsp = JSON.parse(_this.sfzPics[0].upLoadResult[1].data);
						if(uploadRsp.code == 200){
							params.idCardFront = uploadRsp.data.id;
						}else{
							QSApp.showToast('身份证正面上传失败');
							return;
						}
					}catch(e){
						QSApp.showToast('解析身份证正面上传结果失败');
						return;
					}
					
					try{
						let uploadRsp = JSON.parse(_this.sfzPics[1].upLoadResult[1].data);
						if(uploadRsp.code == 200){
							params.idCardReverse = uploadRsp.data.id;
						}else{
							QSApp.showToast('身份证反面上传失败');
							return;
						}
					}catch(e){
						QSApp.showToast('解析身份证反面上传结果失败');
						return;
					}
				
					let url = "/rest/realNameAuth";
					_this.logining = true
					uni.showLoading({
						title:"提交表单，请您耐心等待..."
					})
					_this.$api.request(url, params, failres => {
						_this.logining = false
						uni.hideLoading();
						uni.showToast({
							title: '提交失败',
							icon: "none"
						});
					}).then(rsp => {
						uni.hideLoading();
						console.log(JSON.stringify(rsp));
						_this.logining = false;
						QSApp.showToast('提交成功');
						//跟新到本地缓存
						
						//JS 动态添加属性只能使用["arr"]
						_this.localUserInf["realNameAuth"] = true;
						uni.setStorageSync('userInfo', _this.localUserInf);
						_this.$api.globalData['userInfo'] = _this.localUserInf;
						uni.navigateBack();
					})
					
				}).catch(err => {
					console.log('获取FORM数据失败: ' + JSON.stringify(err));
					QSApp.showToast('获取FORM数据失败');
				});
			},
			commitForm() {
				//上传图片
				let _this = this;
				
				//temp test
				//_this.commitInputForm();
				//return;
				let fileDescribe = "身份证";
				_this.$refs.sfzInfPics.setUpLoadData({fileDescribe:fileDescribe});
				const upload = this.$refs.sfzInfPics.getUpLoadPromiseArray();
				upload.then(res=>{
					//console.log('上传成功:' + JSON.stringify(res));
					console.log('更新:' + JSON.stringify(_this.sfzPics));
					_this.commitInputForm()
					
				}).catch(err=>{
					uni.showToast({
						title: '图片上传失败',
						icon: "none"
					});
					console.log('上传失败:' + JSON.stringify(err));
				})
			},
			navBack() {
				uni.navigateBack();
			},
			setItemDisabled(){
				this.itemDisabled = !this.itemDisabled;
			},
		}
	}
</script>

<style>
.container {
		position: relative;
		width: 100vw;
		height: 100vh;
		overflow: hidden;
		background: #fff;
}
.back-btn {
	position: absolute;
	left: 40upx;
	z-index: 9999;
	padding-top: var(--status-bar-height);
	top: 40upx;
	font-size: 40upx;
	color: $font-color-dark;
}

	
.input-forms{
	margin-top: 30%;
	text-align: center;
}

.buttom-label-btn{
	margin-top: 60upx;
	color: #969696;
	font-size: 16px;
}
</style>
